#include "mainwindow.h"        // 主窗口类的声明
#include "ui_mainwindow.h"     // 主窗口界面（Qt Designer 生成的 UI 类）
//1.音乐播放器界面设置
#include <QIcon>               // 图标类，用于设置按钮图标
#include <QPixmap>             // 图片处理类，用于背景图片
#include <QPalette>            // 调色板类，用于设置背景色或背景图

//2.mp3播放
#include <QMediaPlayer>        // 媒体播放器核心类
#include <QAudioOutput>        // 音频输出类
#include <QDir>                // 文件夹处理类
#include <QFile>               // 文件处理类
#include <QFileInfo>           // 获取文件信息
#include <QMessageBox>         // 弹出对话框
#include <time.h>              // C语言时间函数库，用于随机种子

//3.显示歌词
#include <QJsonDocument>       // JSON文档对象
#include <QJsonArray>          // JSON数组对象
#include <QTextCursor>         // 文本光标操作类
#include <QTextCharFormat>     // 文本格式控制类

//4.调试
#include <QDebug>              // Qt调试输出


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
    m_mode(ORDER_MODE),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
//设置运行窗口的标题，大小，背景
    setWindowTitle("音乐播放器");
    setFixedSize(900, 640);
    setBackGround("C:/Users/G4283/Desktop/image/2.jpg");

//初始化播放控制按钮
    initButton();
//创建播放器和音频输出对象
    m_player = new QMediaPlayer(this);
    m_audioOutput = new QAudioOutput(this);
//默认播放曲目-keainvren.mp3
    QString musicPath = "C:/Users/G4283/Desktop/musiclist/keainvren.mp3";
    m_player->setAudioOutput(m_audioOutput);
    m_player->setSource(QUrl::fromLocalFile(musicPath));
//设置音乐文件夹-musiclist
    m_musicDir = "C:/Users/G4283/Desktop/musiclist";
    loadAppointMusicDir(m_musicDir);
//设置时间种子
    srand(time(NULL));

    lyricsDisplay = new QTextEdit(this);
    lyricsDisplay->setObjectName("lyricsDisplay");
    lyricsDisplay->setReadOnly(true);
    lyricsDisplay->setFont(QFont("Arial", 14));
    lyricsDisplay->setGeometry(500, 100, 370, 400);
    lyricsDisplay->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    loadLyrics("C:/Users/G4283/Desktop/musiclist/keainvren.json");
    connect(m_player, &QMediaPlayer::positionChanged, this, &MainWindow::updateLyrics);
}
//设置背景图
void MainWindow::setBackGround(const QString &filename)
{
    QPixmap pixmap(filename);
    QSize windowSize = this->size();
    QPixmap scalePixmap = pixmap.scaled(windowSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    QPalette palette = this->palette();
    palette.setBrush(QPalette::Window, QBrush(scalePixmap));
    this->setPalette(palette);
}
//设置按钮样式
void MainWindow::setButtonStyle(QPushButton *button, const QString &filename)
{
    button->setFixedSize(50, 50);
    button->setIcon(QIcon(filename));
    button->setIconSize(QSize(button->width(), button->height()));
    button->setStyleSheet("background-color:transparent");
}
//初始化按钮与连接事件
void MainWindow::initButton()
{
    setButtonStyle(ui->pre, "C:/Users/G4283/Desktop/icon2/pre.png");
    setButtonStyle(ui->play, "C:/Users/G4283/Desktop/icon2/play.png");
    setButtonStyle(ui->next, "C:/Users/G4283/Desktop/icon2/next.png");
    setButtonStyle(ui->mode, "C:/Users/G4283/Desktop/icon2/order.png");
    setButtonStyle(ui->list, "C:/Users/G4283/Desktop/icon2/music.png");
    //将按钮与播放，模式，上首，下一首的槽函数连接
    connect(ui->play, &QPushButton::clicked, this, &MainWindow::handlePlaySlot);
    connect(ui->mode, &QPushButton::clicked, this, &MainWindow::handleModeSlot);
    connect(ui->next, &QPushButton::clicked, this, &MainWindow::handleNextSlot);
    connect(ui->pre, &QPushButton::clicked, this, &MainWindow::handlePreSlot);
}
//释放播放器、音频输出、歌词文本框以及 UI 资源，避免内存泄露
MainWindow::~MainWindow()
{
    delete m_player;
    delete m_audioOutput;
    delete lyricsDisplay;
    delete ui;
}
//1.加载歌词
void MainWindow::loadLyrics(const QString &filePath)
{
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "无法打开歌词文件：" << filePath;
        return;
    }

    QByteArray data = file.readAll();
    file.close();

    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(data, &error);
    if (error.error != QJsonParseError::NoError) {
        qDebug() << "解析歌词 JSON 出错：" << error.errorString();
        return;
    }

    if (!doc.isArray()) {
        qDebug() << "歌词 JSON 格式错误，必须是数组形式";
        return;
    }

    QJsonArray lyricsArray = doc.array();
    lyricsList.clear();
    for (const QJsonValue &value : lyricsArray) {
        QJsonArray pair = value.toArray();
        if (pair.size() >= 2) {
            qint64 time = pair[0].toVariant().toLongLong();
            QString text = pair[1].toString();
            lyricsList.append(qMakePair(time, text));
        }
    }

    QStringList allLyrics;
    for (const auto &pair : lyricsList) {
        allLyrics << pair.second;
    }
    lyricsDisplay->setPlainText(allLyrics.join("\n"));
}
//2.更新歌词显示
void MainWindow::updateLyrics(qint64 position)
{
    if (lyricsList.isEmpty()) {
        lyricsDisplay->clear();
        return;
    }

    static int lastLine = -1;
    int currentLine = -1;
    for (int i = 0; i < lyricsList.size(); ++i) {
        if (position >= lyricsList[i].first) {
            if (i == lyricsList.size() - 1 || position < lyricsList[i + 1].first) {
                currentLine = i;
                break;
            }
        }
    }

    if (currentLine == -1 || currentLine == lastLine) return;
    lastLine = currentLine;

    QTextCursor cursor = lyricsDisplay->textCursor();
    cursor.movePosition(QTextCursor::Start);
    cursor.movePosition(QTextCursor::NextBlock, QTextCursor::MoveAnchor, currentLine);

    QTextCharFormat format;
   // format.setForeground(Qt::red);
    format.setFontWeight(QFont::Bold);
    cursor.select(QTextCursor::LineUnderCursor);
    cursor.setCharFormat(format);
    format.setFontPointSize(16);

    lyricsDisplay->setTextCursor(cursor);
    lyricsDisplay->ensureCursorVisible();
}
//3.开始播放音乐
void MainWindow::startPlayMusic()
{
    if (!ui->musiclist->currentItem()) return;

    ui->play->setIcon(QIcon("C:/Users/G4283/Desktop/icon2/play.png"));
    QString musicName = ui->musiclist->currentItem()->text();
    QDir dir(m_musicDir);
    QString musicAbsPath = dir.filePath(musicName + ".mp3");
    m_player->setSource(QUrl::fromLocalFile(musicAbsPath));
    m_player->play();

    QString lyricsPath = dir.filePath(musicName + ".json");
    if (QFile::exists(lyricsPath)) {
        loadLyrics(lyricsPath);
    } else {
        qDebug() << "歌词文件不存在：" << lyricsPath;
        lyricsList.clear();
        lyricsDisplay->clear();
    }
}
//4.上一首按钮事件
void MainWindow::handlePreSlot()
{
    int currentRow = ui->musiclist->currentRow();
    int preRow = 0;
    //根据mode模式来实现代码逻辑
    if (m_mode == ORDER_MODE) {
        preRow = currentRow - 1;
        if (preRow < 0) preRow = ui->musiclist->count() - 1;
    } else if (m_mode == RANDOM_MODE) {
        int cnt = 0;
        do {
            preRow = rand() % ui->musiclist->count();
            cnt++;
        } while ((currentRow == preRow) && (cnt <= 3));
    } else if (m_mode == CIRCLE_MODE) {
        preRow = currentRow;
    }

    ui->musiclist->setCurrentRow(preRow);
    startPlayMusic();
}
//5.下一首按钮事件
void MainWindow::handleNextSlot()
{
    int currentRow = ui->musiclist->currentRow();
    int nextRow = 0;
    //根据mode模式来实现代码逻辑
    if (m_mode == ORDER_MODE) {
        nextRow = (currentRow + 1) % ui->musiclist->count();
    } else if (m_mode == RANDOM_MODE) {
        int cnt = 0;
        do {
            nextRow = rand() % ui->musiclist->count();
            cnt++;
        } while ((currentRow == nextRow) && (cnt <= 3));
    } else if (m_mode == CIRCLE_MODE) {
        nextRow = currentRow;
    }

    ui->musiclist->setCurrentRow(nextRow);
    startPlayMusic();
}
//6.播放模式切换
void MainWindow::handleModeSlot()
{
    if (m_mode == ORDER_MODE) {
        m_mode = RANDOM_MODE;
        ui->mode->setIcon(QIcon("C:/Users/G4283/Desktop/icon2/random.png"));
    } else if (m_mode == RANDOM_MODE) {
        m_mode = CIRCLE_MODE;
        ui->mode->setIcon(QIcon("C:/Users/G4283/Desktop/icon2/circle.png"));
    } else if (m_mode == CIRCLE_MODE) {
        m_mode = ORDER_MODE;
        ui->mode->setIcon(QIcon("C:/Users/G4283/Desktop/icon2/order.png"));
    }
}
//7.播放暂停控制
void MainWindow::handlePlaySlot()
{
    if (m_player->playbackState() == QMediaPlayer::PlayingState) {
        m_player->pause();
        ui->play->setIcon(QIcon("C:/Users/G4283/Desktop/icon2/stop.png"));
    } else {
        m_player->play();
        ui->play->setIcon(QIcon("C:/Users/G4283/Desktop/icon2/play.png"));
    }
}
//8.加载指定文件夹下的音乐
void MainWindow::loadAppointMusicDir(const QString &filepath)
{
    QDir dir(filepath);
    if (!dir.exists()) {
        QMessageBox::warning(this, "文件夹", "文件夹打开失败");
        return;
    }
    //将文件夹中后缀为.mp3的文件加入播放列表
    QFileInfoList fileList = dir.entryInfoList(QDir::Files);
    for (auto element : fileList) {
        if (element.suffix() == "mp3") {
            ui->musiclist->addItem(element.baseName());
        }
    }
    ui->musiclist->setCurrentRow(0);
}
